package com.tienon.message.mq;

import java.util.Random;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import com.ibm.mq.jms.MQConnectionFactory;
import com.ibm.mq.jms.MQQueueConnectionFactory;

public class JMSSender {

	private static MQQueueConnectionFactory mcf;

	private static Connection conn;

	private Session session;

	private static Session[] sessions;

	private Destination dest;

	private static Random rand;

	private MessageProducer producer;
	
	static {
		rand = new Random();

		try {
			mcf = new MQQueueConnectionFactory();
			mcf.setQueueManager("AppMsg");
			mcf.setHostName("www.xiuye.com");
			mcf.setPort(1417);
			conn = mcf.createConnection();
			conn.start();
			sessions = new Session[50];
			for (int i = 0; i < sessions.length; i++) {
				sessions[i] = conn
						.createSession(true, Session.AUTO_ACKNOWLEDGE);
			}
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	public void sendMsg(String msg) throws JMSException {

		session = conn.createSession(true, Session.AUTO_ACKNOWLEDGE);
		dest = session.createQueue("SendMsg");

		this.producer = this.session.createProducer(dest);

		this.producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

		TextMessage m = session.createTextMessage(msg);

		this.producer.send(m);

		session.commit();
	}

	public static void main(String[] args) {

		JMSSender sender = new JMSSender();
		try {

			sender.sendMsg("天用唯勤");
			sender.sendMsg("天地无双");
			sender.sendMsg("天下第一");
			sender.sendMsg("众多");
			sender.sendMsg("都是");
		} catch (JMSException e) {
			e.printStackTrace();
		}

	}

}
